//https://leetcode.cn/problems/4sum/submissions/549957682/

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> ret;

        //1.排序
        sort(nums.begin(), nums.end());

        //2.统计
        for (size_t i = 0; i < nums.size() - 1;)
        {
            for (size_t j = i + 1; j < nums.size() - 1;)
            {

                int left = j + 1, right = nums.size() - 1;
                long long Target = (long long)target - nums[i] - nums[j];
                while (left < right)
                {
                    int sum = nums[left] + nums[right];
                    if (sum > Target)
                        right--;
                    else if (sum < Target)
                        left++;
                    else
                    {
                        ret.push_back({ nums[i],nums[j],nums[left],nums[right] });
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1])
                            left++;
                        while (left < right && nums[right] == nums[right + 1])
                            right--;
                    }
                }
                j++;
                while (j < nums.size() && nums[j] == nums[j - 1])
                    j++;
            }
            i++;
            while (i < nums.size() && nums[i] == nums[i - 1])
                i++;
        }

        return ret;

    }
};